package cp4.work;

import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/cp4/work/login")
public class LoginServlet extends HttpServlet {
    private Map<String, String> accounts = new HashMap<>();

    public LoginServlet() {
        accounts.put("admin", "admin");
        accounts.put("zhangsan", "123123");
        accounts.put("lisi", "123456");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从请求数据中获取用户名和密码
        String name = req.getParameter("username");
        String pass = req.getParameter("password");
        StringUtil.setResponseContent(resp);
        PrintWriter out = resp.getWriter();
        // 判断用户名和密码为空
        if (StringUtil.isEmpty(name) || StringUtil.isEmpty(pass)) {
            out.println("用户名或者密码为空");
            return;
        }
        // 判断用户名信息
        if (!accounts.containsKey(name)) {
            out.println("不存在该账号");
            return;
        }
        // 判断密码
        // 进行jdbc的查询
        if (!accounts.get(name).equals(pass)) {
            out.println("密码不正确");
            return;
        }

        // 登录成功 , 将登录信息保存到session中
        HttpSession session = req.getSession();//获取到session
        session.setAttribute("login_username", name);// 将登录的用户进行存储
        // 跳转到商品页
        resp.sendRedirect("/shop/index.html");
    }
}
